/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.stripes.util;

import com.google.inject.Inject;
import exatrez.stripes.Configuration;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Map;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.antlr.stringtemplate.StringTemplate;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.XMLResource;

/**
 *
 * @author fikri
 */
public class ReportUtil {
     @Inject
    Configuration conf;
    
    private static Logger LOGGER = LoggerFactory.getLogger(ReportUtil.class);   
    

    public byte[] generateReportJasper(String jasperFile, Map parameter) {
        LOGGER.debug("generate report : file = " + jasperFile);
        byte[] bytes = null;

        try {
            String jasperFullPath = jasperFile;
            String reportPath = conf.getProperty("report.path");
            if (StringUtils.isNotBlank(reportPath)) {
                jasperFullPath = reportPath + (reportPath.endsWith(File.separator) ? "" : File.separator) + jasperFile;
            }
            parameter.put("SUBREPORT_DIR", reportPath + (reportPath.endsWith(File.separator) ? "" : File.separator));
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFullPath, parameter, new JREmptyDataSource());
//            JasperExportManager.exportReportToPdfFile(jasperPrint, "C:/Suratreports/JAWABTAWARANTUNAIHAJI.pdf");
            bytes = JasperExportManager.exportReportToPdf(jasperPrint);

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        return bytes;
    }    
    
    
    public byte[] generateReportIText ( String reportName, Map<String,Object> map) {
        
        String reportPath = conf.getProperty("report.path");
        String fullPath = "";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (StringUtils.isNotBlank(reportPath)) {
                fullPath = reportPath + (reportPath.endsWith(File.separator) ? "" : File.separator) + reportName;
            }
        try {
            
            String report = new FileUtil().readAsString(new FileInputStream(new File(fullPath)));
            StringTemplate template = new StringTemplate(report);
            Iterator<String> it = map.keySet().iterator();
                while (it.hasNext()){
                    String key = it.next();
                    LOGGER.debug("key =" + key);
                    template.setAttribute(key, map.get(key));
                }
//            LOGGER.debug("template = " + template.toString());
            gen(template.toString(), baos);
            baos.close();
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage());
            ex.printStackTrace(); // for development used only
        }
        
        return baos.toByteArray();
    }
    
    
    private void gen(String report, ByteArrayOutputStream baos) {        

        try {
//            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//            Document doc = builder.parse();
//            LOGGER.debug("<gen> report :"+report);
            Document doc = XMLResource.load(new ByteArrayInputStream(report.replaceAll("&", "&amp;").getBytes())).getDocument();
//            Document doc = XMLResource.load(new ByteArrayInputStream(report.getBytes())).getDocument();
//            Document doc = XMLResource.load(new ByteArrayInputStream(StringEscapeUtils.unescapeHtml(report.replaceAll("&#146;", "'")).replaceAll("&", "&amp;").getBytes())).getDocument();

//            ITextRenderer renderer = new ITextRenderer();
            ITextRenderer renderer = new ITextRenderer(122.664f,80);
            renderer.setDocument(doc, null);
            renderer.layout();
            renderer.createPDF(baos);
            renderer.finishPDF();
            
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage());
            ex.printStackTrace(); // for development used only
        }
    }

    
}
